package com.hy.admin.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.hy.admin.helper.response.NewsListResponse;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hy.admin.dao.NewsDao;
import com.hy.admin.dao.NewsImageDao;
import com.hy.admin.entity.NewsEntity;
import com.hy.admin.entity.NewsImageEntity;
import com.hy.admin.enums.EnumStatus;
import com.hy.admin.helper.response.NewsResponse;
import com.hy.admin.service.NewsService;
import com.hy.core.response.ServicesResult;
import com.hy.utils.CommonUtility;
import com.hy.utils.OSSUtil;

@Service
public class NewsServiceImpl implements NewsService {
    @Autowired
    private NewsDao newsDao;
    @Autowired
    private NewsImageDao newsImageDao;

    @Override
    public ServicesResult<List<NewsListResponse>> list(Integer pageNum, Integer pageSize) {
        ServicesResult<List<NewsListResponse>> servicesResult = new ServicesResult<>();
        //设置分页条件，Parameters:pageNum 页码pageSize 每页显示数量count 是否进行count查询
        if(pageNum == null || pageNum <= 0){
            //初始页码为1
            pageNum = 1;
        }
        if(pageSize == null || pageSize <= 0){
            //初始数量为20
            pageSize = 20;
        }
        PageHelper.startPage(pageNum, pageSize);

        List<NewsListResponse> newsList = newsDao.selectAll();
        servicesResult.setResult(newsList);
        return servicesResult;
    }

    @Override
    public ServicesResult<NewsResponse> detail(Long id) {
        ServicesResult<NewsResponse> servicesResult = new ServicesResult<>();

        //参数校验
        if (id == null || id <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }

        //查询新闻
        NewsEntity news = newsDao.selectByPrimaryKey(id);
        if(news == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("新闻不存在");
            return servicesResult;
        }
        //查询新闻图片
        List<NewsImageEntity> newsImageList = newsImageDao.selectByNewsId(id);
        //处理返回结果
        NewsResponse newsResponse = new NewsResponse();
        newsResponse.setNews(news);
        newsResponse.setImgList(newsImageList);
        servicesResult.setResult(newsResponse);
        return servicesResult;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public ServicesResult<Boolean> add(NewsEntity newsEntity, MultipartFile[] files) throws Exception {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        if (newsEntity == null){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        if (StringUtils.isBlank(newsEntity.getContent())){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        if (files != null && files.length > 3){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("图片文件过多");
            return servicesResult;
        }
        List<String> imageUrlList = new ArrayList<>();
        if(files!=null && files.length>0) {
            //上传图片至阿里云OSS
            boolean result = true;
            for (MultipartFile file : files) {
                //获取文件名
                String fileName = file.getOriginalFilename();
                String fileType = fileName.substring(fileName.indexOf(".") + 1, fileName.length());
                //使用工具类
                String imagePath = OSSUtil.uploadFile(CommonUtility.multipartToFile(file), fileType);
                if (imagePath == null || StringUtils.isEmpty(imagePath)) {
                    result = false;
                    break;
                }
                imageUrlList.add(imagePath);
            }


            if (imageUrlList == null) {
                //第一个文件上传失败
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("文件上传oss失败");
                return servicesResult;
            }
            if (!result) {//部分图片上传成功
                //图片上传失败---删除上传成功的图片
                OSSUtil.deleteFiles(imageUrlList);
                //删除图片失败---不做处理，每次上传的文件名根据uuid重新生成，对上传失败的文件没有影响
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("文件上传oss失败");
                return servicesResult;
            }
        }

        //保存新闻
        newsDao.insertSelective(newsEntity);
        //保存新闻图片
        if(imageUrlList != null && imageUrlList.size() > 0){

            List<NewsImageEntity> imageList = new ArrayList<>();
            for (String imageUrl : imageUrlList) {
                NewsImageEntity image = new NewsImageEntity();
                Calendar cal = Calendar.getInstance();
                image.setImgPath(imageUrl);
                image.setNewsId(newsEntity.getId());
                image.setCreateTime(cal.getTime());
                image.setUpdateTime(cal.getTime());
                image.setStatus(EnumStatus.VALID.getId());
                imageList.add(image);
            }
            int count = newsImageDao.batchInsert(imageList);
            if (count != imageList.size()) {
                //删除已上传图片
                OSSUtil.deleteFiles(imageUrlList);
                //插入失败，启动事务回滚
                throw new Exception("插入图片失败");
            }
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> update(NewsEntity newsEntity) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        newsEntity.setUpdateTime(new Date());
        int count = newsDao.updateByPrimaryKeySelective(newsEntity);
        if(count <= 0 ){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("修改失败");
            return servicesResult;
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public ServicesResult<Boolean> delete(String ids) throws Exception {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //校验请求参数
        if (StringUtils.isBlank(ids)){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        String[] idArr = ids.split(",");
        List<Long> idList = new ArrayList<>();
        for (String id : idArr){
            idList.add(Long.parseLong(id));
        }
        //删除新闻
        int count = newsDao.deleteByIds(idList);
        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("操作失败");
            return servicesResult;
        }
        //获取图片链接
        List<String> imgList = newsImageDao.selectImgByNewsIds(idList);
        if(imgList != null && imgList.size() > 0) {
            //删除新闻图片
            count = newsImageDao.deleteByNewsIds(idList);
            if (count <= 0) {
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("操作失败");
                throw new Exception("新闻图片删除失败");
            }
            //删除阿里云图片
            count = OSSUtil.deleteFiles(imgList);
            if (count != imgList.size()) {
                servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
                servicesResult.setStatusMsg("图片删除失败");
                throw new Exception("OSS图片删除失败");
            }
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

    @Override
    public ServicesResult<Boolean> updateRecommend(Long id, Integer isRecommend) {
        ServicesResult<Boolean> servicesResult = new ServicesResult<>();
        //参数校验
        if (id == null || id <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("请求报文有误");
            return servicesResult;
        }
        int count = newsDao.updateRecommend(id, isRecommend);
        if(count <= 0){
            servicesResult.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
            servicesResult.setStatusMsg("操作失败");
            return servicesResult;
        }
        servicesResult.setResult(true);
        return servicesResult;
    }

	@Override
	public PageInfo<NewsEntity> listByKeyWord(String keyWord, Integer pageNum, Integer pageSize) {
        if(pageNum == null || pageNum <= 0) pageNum = 1;
        if(pageSize == null || pageSize <= 0) pageSize = 10;
        if(StringUtils.isBlank(keyWord)) keyWord = null;
        Page<NewsEntity> page = PageHelper.startPage(pageNum, pageSize, true);
        newsDao.selectByKeyWord(keyWord);
		return page.toPageInfo();
	}
}
